<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Login\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Login\Form\LoginForm;

class IndexController extends AbstractActionController
{

    protected $form;

    protected $authservice;

    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authservice;
    }

    public function indexAction()
    {
        $form = new LoginForm();
        $error = $this->params()->fromRoute('param');
        $model = new ViewModel(array(
            'form' => $form,
            'error' => $error
        ));
        $model->setTemplate('login/login/index');
        return $model;
    }

    public function processAction()
    {
        $this->getAuthService()
            ->getAdapter()
            ->setIdentity($this->request->getPost('username'))
            ->setCredential($this->request->getPost('password'));
        $result = $this->getAuthService()->authenticate();
        
        if ($result->isValid()) {
            
            $data = $this->getAuthService()
                ->getAdapter()
                ->getResultRowObject(null, 'password');
            $this->getAuthService()
                ->getStorage()
                ->write($data);
            
            return $this->redirect()->toRoute('home');
        } else {            
            return $this->redirect()->toRoute(NULL, array(
                'action' => 'index',
                'param' => '1'
            ));
        }
    }

    public function logoutAction()
    {
         
        $this->getAuthService()->clearIdentity();
        return $this->redirect()->toRoute('Login');
    
    }
}